import { defineStore } from 'pinia';
import Taro from '@tarojs/taro';
const QQMapWX = require('@/utils/qqmap-wx-jssdk.min');

type Location = {
  latitude: string;
  longitude: string;
  address: string;
  cityCode: string;
  cityName: string;
};
const qqmap = new QQMapWX({
  key: 'QSSBZ-WHMKU-QRJVI-22R5D-6M3DF-7YFHN',
});
const useLocationStore = defineStore({
  /** 区分不通状态的唯一标识 */
  id: 'location',
  /** 状态 */
  state: () => ({
    location: {
      latitude: '',
      longitude: '',
      address: '',
      cityCode: '',
      cityName: '',
    },
  }),
  actions: {
    /** 获取经纬度并且地理逆解析 */
    getLocation(): Location {
      if (this.location.cityName) return this.location;
      return this.getReLocation();
    },

    /** 重新定位 */
    async getReLocation(): Promise<Location> {
      this.location = await Taro.getLocation({ type: 'wgs84' });
      return new Promise((resovle, reject) => {
        qqmap.reverseGeocoder({
          location,
          success: (res) => {
            this.location.address = res.result.address;
            this.location.cityName = res.result.ad_info.city.replace('市', '');
            this.location.cityCode = res.result.ad_info.city_code.slice(3);
            this.location.longitude = res.result.ad_info.location.lng;
            this.location.latitude = res.result.ad_info.location.lat;
            resovle(this.location);
          },
          fail: (err) => reject(err),
        });
      });
    },
  },
});
export { useLocationStore };
